package nmrworkflow.framework.gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class FileChooser extends JPanel
{
	public enum Type
	{
		File ("File"),
		Directory ("Directory");
		
		private final String label;
		
		private Type(String label)
		{
			this.label = label;
		}
		
		public String toString()
		{
			return this.label;
		}
	}
	
	private String title;
	private File path;
	private Type type;

	
	public FileChooser(String title, Type type, File initial)
	{
		this.title = title;
		this.type = type;
		this.path = initial;
		setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
		
		setup();
	}
	
	private void setup()
	{
		JLabel titleField = new JLabel(title);
		final JTextField pathField = new JTextField();
		JButton button = new JButton("Select...");
		final JFileChooser chooserDialog = new JFileChooser();
		
		final FileChooser chooser = this;
		
		
		if(type == Type.Directory)
			chooserDialog.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		else
			chooserDialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
		
		chooserDialog.setSelectedFile(path);
		pathField.setText(path.getAbsolutePath());
		
		button.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				int retVal = chooserDialog.showDialog(chooser, "Select " + chooser.getTitle());
				
				if(retVal == JFileChooser.APPROVE_OPTION)
				{
					chooser.setPath( chooserDialog.getSelectedFile() );
					pathField.setText(chooser.getPath().getAbsolutePath());
				}
				
			}
		});
		
		titleField.setPreferredSize(new Dimension(150, 30));
		pathField.setPreferredSize(new Dimension(200, 30));
		
		this.add(titleField);
		this.add(pathField);
		this.add(button);
	}

	public File getPath()
	{
		return path;
	}

	public void setPath(File file)
	{
		this.path = file;
	}
	
	public Type getType()
	{
		return type;
	}
	
	public String getTitle()
	{
		return this.title;
	}
	
	
}
